<?php
/* -------------------------------------------------------------------------------------
* 	ID:						$Id: class.categories.php 520 2015-02-27 17:06:13Z phone.mueller@googlemail.com $
* 	Letzter Stand:			$Revision: 520 $
* 	zuletzt geaendert von:	$Author: siekiera $
* 	Datum:					$Date: 2015-02-27 17:06:13 +0000 (Fri, 27 Feb 2015) $
*
* 	SEO:mercari by Siekiera Media
* 	http://www.seo-mercari.de
*
* 	Copyright (c) since 2011 SEO:mercari
* --------------------------------------------------------------------------------------
* 	based on:
* 	(c) 2000-2001 The Exchange Project  (earlier name of osCommerce)
* 	(c) 2002-2003 osCommerce - www.oscommerce.com
* 	(c) 2003     nextcommerce - www.nextcommerce.org
* 	(c) 2005     xt:Commerce - www.xt-commerce.com
*
* 	Released under the GNU General Public License
* ----------------------------------------------------------------------------------- */

defined('_VALID_XTC') or die('Direct Access to this location is not allowed.');

require_once(DIR_FS_INC.'inc.get_url_friendly_text.php');

class categories {
	var $db;

	function __construct($db) {
		$this->db = $db;
	}

	function remove_categories($category_id) {

		$categories = get_category_tree($category_id, '', '0', '', true);
		$products = array ();
		$products_delete = array ();

		for ($i = 0, $n = sizeof($categories); $i < $n; $i ++) {
			$product_ids = $this->db->db_query("SELECT products_id FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE categories_id = '".$categories[$i]['id']."'");
			while (!$product_ids->EOF) {
				$products[$product_ids->fields['products_id']]['categories'][] = $categories[$i]['id'];
				$product_ids->MoveNext();
			}
		}

		reset($products);
		while(list($key, $value) = each($products)) {
			$category_ids = '';
			for ($i = 0, $n = sizeof($value['categories']); $i < $n; $i ++) {
				$category_ids .= '\''.$value['categories'][$i].'\', ';
			}
			$category_ids = substr($category_ids, 0, -2);

			$check = $this->db->db_query("SELECT COUNT(*) AS total FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE products_id = '".$key."' AND categories_id NOT IN (".$category_ids.")");
			if ($check->fields['total'] < '1')
				$products_delete[$key] = $key;
		}

		@set_time_limit(0);
		for ($i = 0, $n = sizeof($categories); $i < $n; $i ++) {
			$this->remove_category($categories[$i]['id']);
		}

		reset($products_delete);
		while (list ($key) = each($products_delete)) {
			$this->remove_product($key);
		}
	}

	function remove_category($category_id) {

		$category_image = $this->db->db_query("SELECT categories_image FROM ".TABLE_CATEGORIES." WHERE categories_id = ".$this->db->db_prepare($category_id));

		$duplicate_imag = $this->db->db_query("SELECT count(*) AS total FROM ".TABLE_CATEGORIES." WHERE categories_image = ".$this->db->db_prepare($category_image->fields['categories_image']));

		if ($duplicate_image['total'] < 2) {
			if (file_exists(DIR_FS_CATALOG_IMAGES.'categories/'.$category_image->fields['categories_image']))
				@unlink(DIR_FS_CATALOG_IMAGES.'categories/'.$category_image->fields['categories_image']);
		}

		$this->db->db_query("DELETE FROM ".TABLE_CATEGORIES." WHERE categories_id = ".$this->db->db_prepare($category_id));
		$this->db->db_query("DELETE FROM ".TABLE_CATEGORIES_DESCRIPTION." WHERE categories_id = ".$this->db->db_prepare($category_id));
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE categories_id = ".$this->db->db_prepare($category_id));

		if(USE_CACHE == 'true') {
			reset_cache_block('categories');
			reset_cache_block('also_purchased');
		}
		if(MODULE_SEO_URL_INDEX_STATUS == 'True') {
			!$seo_url ? $seo_url = new SeoUrl() : false;
			$seo_url->deleteFromDB('categories_id', $category_id);
		}
	}

	function insert_category($categories_data, $dest_category_id, $action = 'insert') {

		$categories_id = $categories_data['categories_id'];

		$sort_order = $categories_data['sort_order'];
		$categories_status = $categories_data['status'];

		$customers_statuses_array = get_customers_statuses();

		$permission = array ();
		for ($i = 0; $n = sizeof($customers_statuses_array), $i < $n; $i ++) {
			if (isset($customers_statuses_array[$i]['id']))
				$permission[$customers_statuses_array[$i]['id']] = 0;
		}
		if (isset ($categories_data['groups']))
			foreach ($categories_data['groups'] AS $dummy => $b) {
				$permission[$b] = 1;
			}

		if ($permission['all'] == 1) {
			$permission = array ();
			end($customers_statuses_array);
			for ($i = 0; $n = key($customers_statuses_array), $i < $n+1; $i ++) {
				if (isset($customers_statuses_array[$i]['id']))
					$permission[$customers_statuses_array[$i]['id']] = 1;
			}
		}

		$permission_array = array();

		end($customers_statuses_array);
		for ($i = 0; $n = key($customers_statuses_array), $i < $n+1; $i ++)
			if (isset($customers_statuses_array[$i]['id']))
				$permission_array = array_merge($permission_array, array ('group_permission_'.$customers_statuses_array[$i]['id'] => $permission[$customers_statuses_array[$i]['id']]));

		$sql_data_array = array ('sort_order' => $sort_order,
								'categories_status' => $categories_status,
								'num' => $categories_data['num'],
								'products_sorting' => $categories_data['products_sorting'],
								'products_sorting2' => $categories_data['products_sorting2'],
								'categories_template' => $categories_data['categories_template'],
								'products_listing_style' => $categories_data['products_listing_style'],
								'categories_col_top' => $categories_data['categories_col_top'],
								'categories_col_bottom' => $categories_data['categories_col_bottom'],
								'categories_col_left' => $categories_data['categories_col_left'],
								'categories_col_right' => $categories_data['categories_col_right'],
								'category_default_list' => $categories_data['category_default_list'],
								'listing_template' => $categories_data['listing_template']);

		$sql_data_array = array_merge($sql_data_array, $permission_array);
		if ($action == 'insert') {
			$insert_sql_data = array ('parent_id' => $dest_category_id, 'date_added' => 'NOW()');
			$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
			$this->db->db_perform(TABLE_CATEGORIES, $sql_data_array);
			$categories_id = $this->db->db_insert_id();
			
		} elseif ($action == 'update') {
			$update_sql_data = array ('last_modified' => 'NOW()');
			$sql_data_array = array_merge($sql_data_array, $update_sql_data);
			$this->db->db_perform(TABLE_CATEGORIES, $sql_data_array, 'update', 'categories_id = '.$this->db->db_prepare($categories_id));
		}
		set_groups($categories_id, $permission_array);
		$languages = get_languages();

		foreach ($languages AS $lang) {
			$categories_name_array = $categories_data['name'];

			if(!empty($categories_data['categories_url_alias'][$lang['id']]))
				$url_alias = get_url_friendly_text($categories_data['categories_url_alias'][$lang['id']]);

			$sql_data_array = array ('categories_name' => $categories_data['categories_name'][$lang['id']],
									'categories_heading_title' => $categories_data['categories_heading_title'][$lang['id']],
									'categories_description' => stripslashes($categories_data['categories_description_'.$lang['id']]),
									'categories_description_2' => stripslashes($categories_data['categories_description_2_'.$lang['id']]),
									'categories_description_sale' => stripslashes($categories_data['categories_description_sale_'.$lang['id']]),
									'categories_pic_alt' => $categories_data['categories_pic_alt'][$lang['id']],
									'categories_meta_title' => $categories_data['categories_meta_title'][$lang['id']],
									'categories_meta_description' => $categories_data['categories_meta_description'][$lang['id']],
									'categories_meta_keywords' => $categories_data['categories_meta_keywords'][$lang['id']],
									'treepodia_1' => $categories_data['treepodia_1_'.$lang['id']],
									'treepodia_2' => $categories_data['treepodia_2_'.$lang['id']],
									'treepodia_3' => $categories_data['treepodia_3_'.$lang['id']],
									'treepodia_4' => $categories_data['treepodia_4_'.$lang['id']],
									'treepodia_5' => $categories_data['treepodia_5_'.$lang['id']],
									'categories_url_alias' => $url_alias);

			if ($action == 'insert') {
				$insert_sql_data = array ('categories_id' => $categories_id, 'language_id' => $lang['id']);
				$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
				$this->db->db_perform(TABLE_CATEGORIES_DESCRIPTION, $sql_data_array);

			} elseif ($action == 'update')
				$this->db->db_perform(TABLE_CATEGORIES_DESCRIPTION, $sql_data_array, 'update', 'categories_id = '.$this->db->db_prepare($categories_id).' and language_id = '.$this->db->db_prepare($lang['id']));
		}

    $image_paths = getImagePaths(DIR_FS_CATALOG_CATEGORIES_IMAGES, 'DIR_FS_CATALOG');
		if ($categories_image = & try_upload('categories_image', DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES)) {
			$cname_arr = explode('.', $categories_image->filename);
			$cnsuffix = array_pop($cname_arr);

			if(IMAGE_NAME_CATEGORIE == 'c_id')
				$new_categories_name = $categories_id;
			elseif(IMAGE_NAME_CATEGORIE == 'c_name')
				$new_categories_name = $this->checkName(get_url_friendly_text($categories_data['categories_name'][(int)$_SESSION['languages_id']]), $categories_id, $cnsuffix, DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES);
			else
				$new_categories_name = get_url_friendly_text($cname_arr[0]);

			$categories_image_name = $new_categories_name.'.'.$cnsuffix;
			if(DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES.$categories_image->filename != DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES.$categories_image_name) {
				@unlink(DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES.$categories_image_name);
				@rename(DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES.$categories_image->filename, DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES.$categories_image_name);
			}
			$this->db->db_query("UPDATE ".TABLE_CATEGORIES." SET categories_image = ".$this->db->db_prepare($categories_image_name)." WHERE categories_id = '".(int) $categories_id."'");

      foreach($image_paths as $image_path) {
        if ($image_path == 'categories_original_images') {
          processImages(
            DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES,
            constant('DIR_FS_CATALOG_CATEGORIES_IMAGES'),
            $categories_image_name, 'CATEGORY_IMAGE');
        }
        else {
          processImages(
            DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES,
            constant('DIR_FS_CATALOG_'.strtoupper($image_path)),
            $categories_image_name, strtoupper($image_path));
        }
      }
			//require (DIR_WS_INCLUDES.'category_image.php');
		}

		if ($categories_data['del_cat_pic'] == 'yes') {
			@unlink(DIR_FS_CATALOG_CATEGORIES_ORIGINAL_IMAGES.$categories_data['categories_previous_image']);
			@unlink(DIR_FS_CATALOG_CATEGORIES_IMAGES.$categories_data['categories_previous_image']);
			$this->db->db_query("UPDATE ".TABLE_CATEGORIES." SET categories_image = '' WHERE categories_id = '".(int)$categories_id."'");
		}
		
		return $categories_id;
	}

	function set_category_recursive($categories_id, $status = "0") {
		$this->db->db_query("UPDATE ".TABLE_CATEGORIES." SET categories_status = '".$status."' WHERE categories_id = '".$categories_id."'");
		$categories = $this->db->db_query("SELECT categories_id FROM ".TABLE_CATEGORIES." WHERE parent_id='".$categories_id."'");
		while (!$categories->EOF) {
			$this->set_category_recursive($categories->fields['categories_id'], $status);
			$categories->MoveNext();
		}
	}

	function set_category_product_recursive($categories_id, $status = "0") {

		$this->db->db_query("UPDATE ".TABLE_CATEGORIES." SET categories_status = '".$status."' WHERE categories_id = '".$categories_id."'");

		$products2cat = $this->db->db_query("SELECT products_id FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE categories_id = '".$categories_id."'");
		while(!$products2cat->EOF){
			$this->db->db_query("UPDATE ".TABLE_PRODUCTS." SET products_status = '".$status."' WHERE products_id = '".$products2cat['products_id']."'");
			$products2cat->MoveNext();
		}

		$categories = $this->db->db_query("SELECT categories_id FROM ".TABLE_CATEGORIES." WHERE parent_id='".$categories_id."'");
		while (!$categories->EOF) {
			$this->set_category_recursive($categories->fields['categories_id'], $status);
			$categories->MoveNext();
		}
	}

	function move_category($src_category_id, $dest_category_id) {
		$this->db->db_query("UPDATE ".TABLE_CATEGORIES." SET parent_id = ".$this->db->db_prepare($dest_category_id).", last_modified = NOW() WHERE categories_id = ".$this->db->db_prepare($src_category_id));
	}

	function copy_category($src_category_id, $dest_category_id, $ctype = 'link') {
		if(!(in_array($src_category_id, $_SESSION['copied']))) {

			$src_category_id = $src_category_id;
			$dest_category_id = $dest_category_id;

			$ccopy_values = $this->db->db_query("SELECT * FROM ".TABLE_CATEGORIES." WHERE categories_id = '".$src_category_id."'");

			$cdcopy = $this->db->db_query("SELECT * FROM ".TABLE_CATEGORIES_DESCRIPTION." WHERE categories_id = '".$src_category_id."'");

			$sql_data_array = array('parent_id' => $dest_category_id,
									'date_added'=> 'NOW()',
									'last_modified'=> 'NOW()',
									'categories_image' => $ccopy_values->fields['categories_image'],
									'categories_status' => $ccopy_values->fields['categories_status'],
									'categories_template' => $ccopy_values->fields['categories_template'],
									'listing_template' => $ccopy_values->fields['listing_template'],
									'categories_col_top' => $ccopy_values->fields['categories_col_top'],
									'categories_col_bottom' => $ccopy_values->fields['categories_col_bottom'],
									'categories_col_left' => $ccopy_values->fields['categories_col_left'],
									'categories_col_right' => $ccopy_values->fields['categories_col_right'],
									'category_default_list' => $ccopy_values->fields['category_default_list'],
									'sort_order' => $ccopy_values->fields['sort_order'],
									'products_sorting' => $ccopy_values->fields['products_sorting'],
									'products_sorting2' => $ccopy_values->fields['products_sorting2']);

			$customers_statuses_array = get_customers_statuses();

			for ($i = 0; $n = sizeof($customers_statuses_array), $i < $n; $i ++) {
				if (isset($customers_statuses_array[$i]['id']))
					$sql_data_array = array_merge($sql_data_array, array ('group_permission_'.$customers_statuses_array[$i]['id'] => $product->fields['group_permission_'.$customers_statuses_array[$i]['id']]));
			}

			$this->db->db_perform(TABLE_CATEGORIES, $sql_data_array);

			$new_cat_id = $this->db->db_insert_id();

			$_SESSION['copied'][] = $new_cat_id;

			$product = $this->db->db_query("SELECT products_id FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE categories_id = '".$src_category_id."'");
			while (!$product->EOF) {
				if ($ctype == 'link')
					$this->link_product($product->fields['products_id'], $new_cat_id);
				elseif ($ctype == 'duplicate')
					$this->duplicate_product($product->fields['products_id'], $new_cat_id);
				else
					die('Undefined copy type!');
				
				$product->MoveNext();
			}

			$src_pic = DIR_FS_CATALOG_IMAGES.'categories/'.$ccopy_values->fields['categories_image'];
			if (is_file($src_pic)) {
				$get_suffix = explode('.', $ccopy_values->fields['categories_image']);
				$suffix = array_pop($get_suffix);
				$dest_pic = $new_cat_id.'.'.$suffix;
				@copy($src_pic, DIR_FS_CATALOG_IMAGES.'categories/'.$dest_pic);
				$this->db->db_query("UPDATE ".TABLE_CATEGORIES." SET categories_image = '".$dest_pic."' WHERE categories_id = '".$new_cat_id."'");
			}

			while (!$cdcopy->EOF) {
				$this->db->db_query("INSERT INTO 
										".TABLE_CATEGORIES_DESCRIPTION." 
											(categories_id, 
											language_id, 
											categories_name, 
											categories_heading_title, 
											categories_description, 
											categories_meta_title, 
											categories_meta_description, 
											categories_meta_keywords,
											categories_url_alias) 
									VALUES 
										('".$new_cat_id."', 
										'".$cdcopy->fields['language_id']."', 
										'".addslashes($cdcopy->fields['categories_name'])."', 
										'".addslashes($cdcopy->fields['categories_heading_title'])."', 
										'".addslashes($cdcopy->fields['categories_description'])."', 
										'".addslashes($cdcopy->fields['categories_meta_title'])."', 
										'".addslashes($cdcopy->fields['categories_meta_description'])."', 
										'".addslashes($cdcopy->fields['categories_meta_keywords'])."',
										'".addslashes($cdcopy->fields['categories_url_alias'])."')");
				$cdcopy->MoveNext();
			}

			$crcopy = $this->db->db_query("SELECT categories_id FROM ".TABLE_CATEGORIES." WHERE parent_id = '".$src_category_id."'");

			while (!$crcopy->EOF) {
				$this->copy_category($crcopy->fields['categories_id'], $new_cat_id, $ctype);
				if(MODULE_SEO_URL_INDEX_STATUS == 'True') {
					
					!$seo_url ? $seo_url = new SeoUrl() : false;
					$seo_url->insertSeoDBTable('category', $new_cat_id);
				}
				$crcopy->MoveNext();
			}
		}
		return $new_cat_id;
	}

	function remove_product($product_id) {

		$product_content = $this->db->db_query("SELECT content_file FROM ".TABLE_PRODUCTS_CONTENT." WHERE products_id = ".$this->db->db_prepare($product_id));

		while (!$product_content->EOF) {
	   		$duplicate_content = $this->db->db_query("SELECT
	   														count(*) AS total
	   													FROM
	   														".TABLE_PRODUCTS_CONTENT."
	   													WHERE
	   														content_file = ".$this->db->db_prepare($product_content->fields['content_file'])."
	   													AND
	   														products_id != ".$this->db->db_prepare($product_id));

	   		if ($duplicate_content->fields['total'] == 0)
	   			@unlink(DIR_FS_DOCUMENT_ROOT.'media/products/'.$product_content->fields['content_file']);

	   		$this->db->db_query("DELETE FROM
	   								".TABLE_PRODUCTS_CONTENT."
	   							WHERE
	   								products_id = ".$this->db->db_prepare($product_id)."
	   							AND
	   								(content_file = '".$product_content->fields['content_file']."' OR content_file = '')");
			$product_content->MoveNext();
		}

		$product_image = $this->db->db_query("SELECT
													products_image
												FROM
													".TABLE_PRODUCTS."
												WHERE
													products_id = ".$this->db->db_prepare($product_id));


		$duplicate_image = $this->db->db_query("SELECT
													count(*) AS total
												FROM
													".TABLE_PRODUCTS."
												WHERE
													products_image = ".$this->db->db_prepare($product_image->fields['products_image']));

		if ($duplicate_image->fields['total'] < 2)
			del_image_file($product_image->fields['products_image']);

		$mo_images = $this->db->db_query("SELECT
											image_name
										FROM
											".TABLE_PRODUCTS_IMAGES."
										WHERE
											products_id = ".$this->db->db_prepare($product_id));
		while (!$mo_images->EOF) {
			$duplicate_more_image = $this->db->db_query("SELECT
															count(*) AS total
														FROM
															".TABLE_PRODUCTS_IMAGES."
														WHERE
															image_name = '".$mo_images->fields['image_name']."'");
			if ($duplicate_more_image->fields['total'] < 2)
				del_image_file($mo_images->fields['image_name']);
			$mo_images->MoveNext();
		}

		$this->db->db_query("DELETE FROM ".TABLE_SPECIALS." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_IMAGES." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_TAG_TO_PRODUCT." WHERE pID = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_ATTRIBUTES." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_CUSTOMERS_BASKET." WHERE products_id = ".$this->db->db_prepare($product_id));
		$this->db->db_query("DELETE FROM ".TABLE_CUSTOMERS_BASKET_ATTRIBUTES." WHERE products_id = ".$this->db->db_prepare($product_id));

		$customers_status_array = get_customers_statuses();
		for ($i = 0, $n = sizeof($customers_status_array); $i < $n; $i ++) {
			if (isset($customers_statuses_array[$i]['id']))
				$this->db->db_query("DELETE FROM
										".TABLE_PERSONAL_OFFERS_BY.$customers_statuses_array[$i]['id']."
									WHERE
										products_id = ".$this->db->db_prepare($product_id));
		}

		$product_reviews = $this->db->db_query("SELECT
													reviews_id
												FROM
													".TABLE_REVIEWS."
												WHERE
													products_id = ".$this->db->db_prepare($product_id));
		while(!$product_reviews->EOF) {
			$this->db->db_query("DELETE FROM
									".TABLE_REVIEWS_DESCRIPTION."
								WHERE
									reviews_id = '".$product_reviews->fields['reviews_id']."'");
			$product_reviews->MoveNext();
		}

		$this->db->db_query("DELETE FROM
									".TABLE_REVIEWS."
								WHERE
									products_id = ".$this->db->db_prepare($product_id));

		if (USE_CACHE == 'true') {
			reset_cache_block('categories');
			reset_cache_block('also_purchased');
		}
		
		if(MODULE_SEO_URL_INDEX_STATUS == 'True') {
			!$seo_url ? $seo_url = new SeoUrl() : false;
			$seo_url->deleteFromDB('products_id', $product_id);
		}
	}

	function delete_product($product_id, $product_categories = '') {

		$this->db->db_query("DELETE FROM
								".TABLE_PRODUCTS_TO_CATEGORIES."
							WHERE
								products_id = ".$this->db->db_prepare($product_id));

		$product_categories = $this->db->db_query("SELECT
														COUNT(*) AS total
													FROM
														".TABLE_PRODUCTS_TO_CATEGORIES."
													WHERE
														products_id = ".$this->db->db_prepare($product_id));
														
		if($product_categories->fields['total'] == '0') 
			$this->remove_product($product_id);
		
	}
	
	function insert_product_image($filename, $products_id, $products_name, $idx=0) {
    global $message_stack;

    if (!file_exists($filename)) {
      $message_stack->add('Bilddatei nicht gefunden ('. $filename . ')', 'error');
			//echo_e('Bilddatei nicht gefunden ('. $filename . ')');
      return false;
    }
    if (is_dir($filename)) {
      $message_stack->add('keine Bilddatei angegeben ('. $products_name . ')', 'error');
			//echo_e('keine Bilddatei angegeben ('. $products_name . ')');
      return false;
    }

    $pathinfo = pathinfo($filename);
    if(IMAGE_NAME_PRODUCT == 'p_id')
      $new_products_name = $products_id;
    elseif(IMAGE_NAME_PRODUCT == 'p_name')
      $new_products_name = $this->checkName(get_url_friendly_text($products_name), $products_id, $pathinfo['extension']);
    else
		  $new_products_name = get_url_friendly_text($pathinfo['filename']);

    $products_image_name = $new_products_name.($idx===0 ? '' : '-'.$idx).'.'.$pathinfo['extension'];
		if(file_exists(DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name))
			unlink(DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);
    copy($filename, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);

    $image_paths = getImagePaths(DIR_FS_CATALOG_PRODUCTS_IMAGES, 'DIR_FS_CATALOG');
    foreach($image_paths as $image_path) {
      if ($image_path != 'original_images') {
        $parameter_path = explode('_', $image_path);
        $parameter_path = 'product_image_'.$parameter_path[0];
        processImages(
          DIR_FS_CATALOG_ORIGINAL_IMAGES,
          constant('DIR_FS_CATALOG_'.strtoupper($image_path)),
          $products_image_name, strtoupper($parameter_path));
      }
    }

/*
		require (DIR_WS_INCLUDES.'product_icon_images.php');
		require (DIR_WS_INCLUDES.'product_thumbnail_images.php');
		require (DIR_WS_INCLUDES.'product_info_images.php');
		require (DIR_WS_INCLUDES.'product_popup_images.php'); */
		return $products_image_name;
  }

	function insert_product($products_data, $dest_category_id, $action = 'insert') {
	$products_id = $products_data['products_id'];
		$products_date_available = $products_data['products_date_available'];

		$products_date_available = (date('Y-m-d') < $products_date_available) ? $products_date_available : 'null';

		if($products_data['products_startpage'] == 1 ) {
			$this->link_product($products_data['products_id'], 0);
			$products_status = 1;
		
		}
    else {
			$products_status = $products_data['products_status'];
			$this->unlink_product_from_startpage($products_data['products_id']);
    }

    if ($products_status == 1
        && isset($products_data['products_status_model']) && $products_data['products_status_model'] == 1)
      $products_status = 2;
		
		$products_data['products_price'] = str_replace(',','.',$products_data['products_price']);
		if (PRICE_IS_BRUTTO == 'true' && $products_data['products_price'])
			$products_data['products_price'] = round(($products_data['products_price'] / (get_tax_rate($products_data['products_tax_class_id']) + 100) * 100), PRICE_PRECISION);

		$customers_statuses_array = get_customers_statuses();

		$permission = array();
		for ($i = 0; $n = sizeof($customers_statuses_array), $i < $n; $i ++) {
			if (isset($customers_statuses_array[$i]['id']))
				$permission[$customers_statuses_array[$i]['id']] = 0;
		}
		if (isset ($products_data['groups'])) {
			foreach ($products_data['groups'] AS $dummy => $b) {
				$permission[$b] = 1;
			}
		}
		if ($permission['all']==1) {
			$permission = array();
			end($customers_statuses_array);
			for ($i = 0; $n = key($customers_statuses_array), $i < $n+1; $i ++) {
				if (isset($customers_statuses_array[$i]['id']))
					$permission[$customers_statuses_array[$i]['id']] = 1;
			}
		}

		$permission_array = array();

		end($customers_statuses_array);
		for ($i = 0; $n = key($customers_statuses_array), $i < $n+1; $i ++) {
			if (isset($customers_statuses_array[$i]['id'])) {
				$permission_array = array_merge($permission_array, array ('group_permission_'.$customers_statuses_array[$i]['id'] => $permission[$customers_statuses_array[$i]['id']]));
			}
		}

		$sql_data_array = array(
      'products_quantity' => $products_data['products_quantity'],
      'products_model' => $products_data['products_model'],
      'products_ean' => $products_data['products_ean'],
      'products_isbn' => $products_data['products_isbn'],
      'products_price' => $products_data['products_price'],
      'products_sort' => $products_data['products_sort'],
      'products_shippingtime' => $products_data['shipping_status'],
      'products_discount_allowed' => $products_data['products_discount_allowed'],
      'products_date_available' => $products_date_available,
      'products_weight' => str_replace(',', '.', $products_data['products_weight']),
      'products_status' => $products_status,
      'products_startpage' => $products_data['products_startpage'],
      'products_startpage_sort' => $products_data['products_startpage_sort'],
      'products_tax_class_id' => $products_data['products_tax_class_id'],
      'product_template' => $products_data['info_template'],
      'options_template' => $products_data['options_template'],
      'products_list_overlay' => $products_data['products_list_overlay'],
      'brand_id' => $products_data['brand_id'],
      'products_content_id' => $products_data['products_content_id'],
      'products_fsk18' => $products_data['products_fsk18'],
      'products_usk' => ($products_data['products_fsk18'] == 1 ? $products_data['products_usk'] : ''),
      'products_stock' => $products_data['products_stock'],
      'products_movie_url' => $products_data['products_movie_url'],
      'products_col_left' => $products_data['products_col_left'],
      'products_col_right' => $products_data['products_col_right'],
      'products_col_top' => $products_data['products_col_top'],
      'products_col_bottom' => $products_data['products_col_bottom'],
      'products_info' => $products_data['products_info'],
      'products_vpe_value' => $products_data['products_vpe_value'],
      'products_vpe_status' => $products_data['products_vpe_status'],
      'products_vpe' => $products_data['products_vpe'],
      'products_tell_a_friend' => $products_data['products_tell_a_friend'],
      'products_ask_to_product' => $products_data['products_ask_to_product'],
      'products_shipping_costs' => $products_data['products_shipping_costs'],
      'products_treepodia' => $products_data['products_treepodia'],
      'products_zustand' => $products_data['products_zustand']);

		$sql_data_array = array_merge($sql_data_array, $permission_array);

		if (!$products_id || $products_id == '') {
			$new_pid =  $this->db->db_query("SHOW TABLE STATUS LIKE '".TABLE_PRODUCTS."'");
			$products_id = $new_pid->fields['Auto_increment'];
		}

		if ($products_image = try_upload('products_image', DIR_FS_CATALOG_ORIGINAL_IMAGES, '777', '')) {

			$pname_arr = explode('.', $products_image->filename);
			$nsuffix = array_pop($pname_arr);

      $products_image_name = insert_product_image(
        $products_image->filename, $products_id, $products_data['products_name'][(int)$_SESSION['languages_id']], $idx=0);
/*
			if(IMAGE_NAME_PRODUCT == 'p_id')
				$new_products_name = $products_id;
			elseif(IMAGE_NAME_PRODUCT == 'p_name')
				$new_products_name = $this->checkName(get_url_friendly_text($products_data['products_name'][(int)$_SESSION['languages_id']]), $products_id);
			else
				$new_products_name = get_url_friendly_text($pname_arr[0]);

			$products_image_name = $new_products_name.'.'.strtolower($nsuffix);
*/			
			$dup_check =  $this->db->db_query("SELECT COUNT(*) AS total FROM ".TABLE_PRODUCTS." WHERE products_image = '".$products_data['products_previous_image_0']."'");

			if($dup_check->fields['total'] < 2)
				@del_image_file($products_data['products_previous_image_0']);

			$dup_check = $this->db->db_query("SELECT COUNT(*) AS total FROM ".TABLE_PRODUCTS." WHERE products_image = '".$products_image->filename."'");
			if ($dup_check->fields['total'] == 0) {
				rename(DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image->filename, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);
			} else {
				copy(DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image->filename, DIR_FS_CATALOG_ORIGINAL_IMAGES.$products_image_name);
			}
			$sql_data_array['products_image'] = $products_image_name;
/*
			require (DIR_WS_INCLUDES.'product_icon_images.php');
			require (DIR_WS_INCLUDES.'product_thumbnail_images.php');
			require (DIR_WS_INCLUDES.'product_info_images.php');
			require (DIR_WS_INCLUDES.'product_popup_images.php');
*/
		} else
			$products_image_name = $products_data['products_previous_image_0'];

//echo_e('.', 'E');
		if ($products_data['del_pic'] != '') {
			$dup_check =  $this->db->db_query("SELECT COUNT(*) AS total FROM ".TABLE_PRODUCTS." WHERE products_image = '".$products_data['del_pic']."'");
			if ($dup_check->fields['total'] < 2)
				@del_image_file($products_data['del_pic']);
			 $this->db->db_query("UPDATE ".TABLE_PRODUCTS." SET products_image = '' WHERE products_id = ".$this->db->db_prepare($products_id));
		}

		if ($products_data['del_mo_pic'] != '') {
			foreach ($products_data['del_mo_pic'] AS $dummy => $val) {
				$dup_check =  $this->db->db_query("SELECT COUNT(*) AS total FROM ".TABLE_PRODUCTS_IMAGES." WHERE image_name = '".$val."'");
				if ($dup_check->fields['total'] < 2)
					@del_image_file($val);
				$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_IMAGES." WHERE products_id = ".$this->db->db_prepare($products_id)." AND image_name  = '".$val."'");
			}
		}

		$languages = get_languages();

		for ($img = 0; $img < MO_PICS; $img ++) {
			if ($pIMG = & try_upload('mo_pics_'.$img, DIR_FS_CATALOG_ORIGINAL_IMAGES, '777', '')) {
				$pname_arr = explode('.', $pIMG->filename);
				$nsuffix = array_pop($pname_arr);

				if(IMAGE_NAME_PRODUCT == 'p_id')
					$new_products_name = $products_id;
				elseif(IMAGE_NAME_PRODUCT == 'p_name')
					$new_products_name = $this->checkName(get_url_friendly_text($this->db->db_prepare($products_data['products_name'][(int)$_SESSION['languages_id']])), $products_id);
				else
					$new_products_name = get_url_friendly_text($pname_arr[0]);

				$products_image_name = $new_products_name.'-'. ($img +1).'.'.strtolower($nsuffix);
				$dup_check = $this->db->db_query("SELECT
														COUNT(*) AS total
													FROM
														".TABLE_PRODUCTS_IMAGES."
													WHERE
														image_name = '".$products_data['products_previous_image_'. ($img+1)]."'");
				if ($dup_check->fields['total'] < 2)
					@del_image_file($products_data['products_previous_image_'. ($img+1)]);

				@del_image_file($products_image_name);

				rename(DIR_FS_CATALOG_ORIGINAL_IMAGES.'/'.$pIMG->filename, DIR_FS_CATALOG_ORIGINAL_IMAGES.'/'.$products_image_name);
				$mo_img = array('products_id' => $products_id,
								'image_nr' => ($img +1),
								'image_name' => $products_image_name);

				if ($action == 'insert') {
					$this->db->db_perform(TABLE_PRODUCTS_IMAGES, $mo_img);

				} elseif ($action == 'update' && $products_data['products_previous_image_'. ($img+1)]) {
					if ($products_data['del_mo_pic']) {
						foreach ($products_data['del_mo_pic'] AS $dummy => $val) {
							if ($val == $products_data['products_previous_image_'. ($img+1)])
								$this->db->db_perform(TABLE_PRODUCTS_IMAGES, $mo_img);
							break;
						}
					}
					$this->db->db_perform(TABLE_PRODUCTS_IMAGES, $mo_img, 'update', 'image_name = \''.$this->db->db_prepare($products_data['products_previous_image_'. ($img+1)]).'\'');

				} elseif (!$products_data['products_previous_image_'. ($img +1)])
					$this->db->db_perform(TABLE_PRODUCTS_IMAGES, $mo_img);
				
				require (DIR_WS_INCLUDES.'product_icon_images.php');
				require (DIR_WS_INCLUDES.'product_thumbnail_images.php');
				require (DIR_WS_INCLUDES.'product_info_images.php');
				require (DIR_WS_INCLUDES.'product_popup_images.php');

			}
			foreach($languages AS $lang) {
				$alt_tag = array('alt_langID_'.$lang['id'] => $products_data['alt_tag_'.($img+1).'_'.$lang['id']]);
				$this->db->db_perform(TABLE_PRODUCTS_IMAGES, $alt_tag, 'update', 'image_nr = \''.($img+1).'\' AND products_id = '.$products_id);
			}
		}

		if (isset ($products_data['products_image']) && not_null($products_data['products_image']) && ($products_data['products_image'] != 'none'))
			$sql_data_array['products_image'] = $this->db->db_prepare($products_data['products_image']);

		if ($action == 'insert') {
			$insert_sql_data = array ('products_date_added' => 'NOW()');
			$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
			$this->db->db_perform(TABLE_PRODUCTS, $sql_data_array);
			$products_id = $this->db->db_insert_id();
		
		} elseif ($action == 'update') {
			$update_sql_data = array ('products_last_modified' => 'NOW()');
			$sql_data_array = array_merge($sql_data_array, $update_sql_data);
			$this->db->db_perform(TABLE_PRODUCTS, $sql_data_array, 'update', 'products_id = '.$this->db->db_prepare($products_id));
		}
		$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_TO_CATEGORIES." WHERE products_id = '".$products_id."'");
		
		$this->db->db_query("DELETE FROM 
								".TABLE_PRODUCTS_TO_CATEGORIES." 
							WHERE 
								products_id = '".$products_id."'
							AND
								categories_id != '0'");	
		foreach($_POST['cPath'] AS $categorie_id) {
			$this->db->db_query("INSERT INTO ".TABLE_PRODUCTS_TO_CATEGORIES."
									(products_id, categories_id)
								VALUES
									('".$products_id."', '".$categorie_id."')");
		}
		
		$languages = get_languages();

		$i = 0;
		$group = $this->db->db_query("SELECT customers_status_id FROM ".TABLE_CUSTOMERS_STATUS." WHERE language_id = '".(int)$_SESSION['languages_id']."' AND customers_status_id != '0'");
		while(!$group->EOF) {
			$i++;
			$group_data[$i] = array ('STATUS_ID' => $group->fields['customers_status_id']);
			$group->MoveNext();
		}
		
		include(DIR_WS_MODULES.'specials_price.php');
		
		for ($col = 0, $n = sizeof($group_data); $col < $n +1; $col ++) {
			if ($group_data[$col]['STATUS_ID'] != '') {
				$personal_price = str_replace(',', '.', $products_data['products_price_'.$group_data[$col]['STATUS_ID']]);
				if ($personal_price == '' || $personal_price == '0.0000') {
					$personal_price = '0.00';
					
				} else {
					if(PRICE_IS_BRUTTO == 'true')
						$personal_price = ($personal_price / (get_tax_rate($products_data['products_tax_class_id']) + 100) * 100);

					$personal_price = round($personal_price, PRICE_PRECISION);
				}

				if ($action == 'insert') {

					$this->db->db_query("DELETE FROM 
												".TABLE_PERSONAL_OFFERS_BY.$group_data[$col]['STATUS_ID']." 
											WHERE 
												products_id = '".$products_id."'
											AND 
												quantity = '1'");

					$insert_array = array ();
					$insert_array = array ('personal_offer' => $personal_price, 'quantity' => '1', 'products_id' => $products_id);
					$this->db->db_perform(TABLE_PERSONAL_OFFERS_BY.$group_data[$col]['STATUS_ID'], $insert_array);

				} else {

					$this->db->db_query("UPDATE
											".TABLE_PERSONAL_OFFERS_BY.$group_data[$col]['STATUS_ID']."
										SET
											personal_offer = '".$personal_price."'
										WHERE
											products_id = '".$products_id."'
										AND
											quantity = '1'");
				}
			}
		}
		
		$this->db->db_query("DELETE FROM ".TABLE_TAG_TO_PRODUCT." WHERE pID = '".$products_id."'");
		foreach($languages AS $lang) {
			$language_id = $lang['id'];
			$products_url_alias = get_url_friendly_text($products_data['products_url_alias'][$language_id]);
			$sql_data_array = array ('products_name' => $products_data['products_name'][$language_id],
									'products_description' => stripslashes($products_data['products_description_'.$language_id]),
									'products_short_description' => stripslashes($products_data['products_short_description_'.$language_id]),
									'products_img_alt' => $products_data['products_image_alt_'.$language_id],
									'products_keywords' => $products_data['products_keywords'][$language_id],
									'products_url' => $products_data['products_url'][$language_id],
									'products_meta_title' => $products_data['products_meta_title'][$language_id],
									'products_meta_description' => $products_data['products_meta_description'][$language_id],
									'products_meta_keywords' => $products_data['products_meta_keywords'][$language_id],
									'products_url_alias' => $products_url_alias,
									'treepodia_1' => $products_data['treepodia_1_'.$language_id],
									'treepodia_2' => $products_data['treepodia_2_'.$language_id],
									'treepodia_3' => $products_data['treepodia_3_'.$language_id],
									'treepodia_4' => $products_data['treepodia_4_'.$language_id],
									'treepodia_5' => $products_data['treepodia_5_'.$language_id]);

			if(!empty($products_data['products_tag_cloud'][$language_id])) {
				$db = $this->db->db_query("DELETE FROM ".TABLE_TAG_TO_PRODUCT." WHERE pID = '".$products_id."' AND lID = '".$language_id."'");
				foreach ($products_data['products_tag_cloud'][$language_id] AS $tag) {
					if(!empty($tag))
						$this->db->db_query("INSERT INTO ".TABLE_TAG_TO_PRODUCT." VALUES ('','".$products_id."','".$language_id."','".trim($tag)."') ");
				}
			}

			if ($action == 'insert') {
				$insert_sql_data = array ('products_id' => $products_id, 'language_id' => $language_id);
				$sql_data_array = array_merge($sql_data_array, $insert_sql_data);
				$this->db->db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array);

			} elseif ($action == 'update')
				$this->db->db_perform(TABLE_PRODUCTS_DESCRIPTION, $sql_data_array, 'update', 'products_id = '.$this->db->db_prepare($products_id).' AND language_id = \''.$language_id.'\'');
		}
		return $products_id;
	}

	function duplicate_product($src_products_id, $dest_categories_id) {

		$product = $this->db->db_query("SELECT * FROM ".TABLE_PRODUCTS." WHERE products_id = ".$this->db->db_prepare($src_products_id));

		if ($dest_categories_id == 0) {
			$startpage = 1;
			$products_status = 1;
		} else {
			$startpage= 0;
			$products_status = $product->fields['products_status'];
		}

		$sql_data_array = array('products_quantity' => $product->fields['products_quantity'],
							'products_model' => $product->fields['products_model'],
							'products_ean' => $product->fields['products_ean'],
							'products_shippingtime' => $product->fields['products_shippingtime'],
							'products_sort' => $product->fields['products_sort'],
							'products_startpage' => $startpage,
							'products_sort' => $product->fields['products_sort'],
							'products_price' => $product->fields['products_price'],
							'products_discount_allowed' => $product->fields['products_discount_allowed'],
							'products_date_added' => date('Y-m-d H:m:s'),
							'products_date_available' => $product->fields['products_date_available'],
							'products_weight' => $product->fields['products_weight'],
							'products_status' => $products_status,
							'products_tax_class_id' => $product->fields['products_tax_class_id'],
							'brand_id' => $product->fields['brand_id'],
							'product_template' => $product->fields['product_template'],
							'options_template' => $product->fields['options_template'],
							'products_fsk18' => $product->fields['products_fsk18'],
							'products_vpe' => $product->fields['products_vpe'],
							'products_vpe_value' => $product->fields['products_vpe_value'],
							'products_vpe_status' => $product->fields['products_vpe_status'],
							'products_list_overlay' => $product->fields['products_list_overlay'],
							'products_startpage_sort' => $product->fields['products_startpage_sort'],
							'products_movie_url' => $product->fields['products_movie_youtube_id'],
							'products_col_top' => $product->fields['products_col_top'],
							'products_col_left' => $product->fields['products_col_left'],
							'products_col_right' => $product->fields['products_col_right'],
							'products_col_bottom' => $product->fields['products_col_bottom'],
							'products_info' => $product->fields['products_info'],
							'products_shipping_costs' => $product->fields['products_shipping_costs'],
							'products_treepodia' => $product->fields['products_treepodia'],
							'products_zustand' => $product->fields['products_zustand']);

		$customers_statuses_array = get_customers_statuses();

		for ($i = 0; $n = sizeof($customers_statuses_array), $i < $n; $i ++) {
			if (isset($customers_statuses_array[$i]['id']))
				$sql_data_array = array_merge($sql_data_array, array ('group_permission_'.$customers_statuses_array[$i]['id'] => $product->fields['group_permission_'.$customers_statuses_array[$i]['id']]));

		}

		$this->db->db_perform(TABLE_PRODUCTS, $sql_data_array);

		$dup_products_id = $this->db->db_insert_id();

		if($product->fields['products_image'] != '') {

			$pname_arr = explode('.', $product->fields['products_image']);
			$nsuffix = array_pop($pname_arr);
			$dup_products_image_name = $dup_products_id.'_0.'.strtolower($nsuffix);

			$this->db->db_query("UPDATE ".TABLE_PRODUCTS." SET products_image = '".$dup_products_image_name."' WHERE products_id = '".$dup_products_id."'");

			@copy(DIR_FS_CATALOG_ORIGINAL_IMAGES.'/'.$product->fields['products_image'], DIR_FS_CATALOG_ORIGINAL_IMAGES.'/'.$dup_products_image_name);
			@copy(DIR_FS_CATALOG_INFO_IMAGES.'/'.$product->fields['products_image'], DIR_FS_CATALOG_INFO_IMAGES.'/'.$dup_products_image_name);
			@copy(DIR_FS_CATALOG_THUMBNAIL_IMAGES.'/'.$product->fields['products_image'], DIR_FS_CATALOG_THUMBNAIL_IMAGES.'/'.$dup_products_image_name);
			@copy(DIR_FS_CATALOG_ICON_IMAGES.'/'.$product->fields['products_image'], DIR_FS_CATALOG_ICON_IMAGES.'/'.$dup_products_image_name);
			@copy(DIR_FS_CATALOG_POPUP_IMAGES.'/'.$product->fields['products_image'], DIR_FS_CATALOG_POPUP_IMAGES.'/'.$dup_products_image_name);

		} else
			unset ($dup_products_image_name);

		$description = $this->db->db_query("SELECT * FROM ".TABLE_PRODUCTS_DESCRIPTION." WHERE products_id = ".$this->db->db_prepare($src_products_id));

		$old_products_id = $this->db->db_prepare($src_products_id);
		while (!$description->EOF) {
			$this->db->db_query("INSERT INTO 
									".TABLE_PRODUCTS_DESCRIPTION."
	    		                 SET 
									products_id                	= '".$dup_products_id."',
									language_id                		= '".$description->fields['language_id']."',
									products_name              	= '".addslashes($description->fields['products_name'])."',
									products_description       	= '".addslashes($description->fields['products_description'])."',
									products_keywords          	= '".addslashes($description->fields['products_keywords'])."',
									products_short_description = '".addslashes($description->fields['products_short_description'])."',
									products_meta_title        	= '".addslashes($description->fields['products_meta_title'])."',
									products_meta_description = '".addslashes($description->fields['products_meta_description'])."',
									products_meta_keywords  = '".addslashes($description->fields['products_meta_keywords'])."',
									products_url               		= '".$description->fields['products_url']."',
									products_viewed            	= '0',
									products_tag_cloud			= '".addslashes($description->fields['products_tag_cloud'])."',
									products_url_alias			= '".addslashes($description->fields['products_url_alias'])."'");
			$description->MoveNext();
		}

		$this->db->db_query("INSERT INTO ".TABLE_PRODUCTS_TO_CATEGORIES." SET products_id   = '".$dup_products_id."', categories_id = ".$this->db->db_prepare($dest_categories_id));

		$mo_images = get_products_mo_images($src_products_id);
		if (is_array($mo_images)) {
			foreach ($mo_images AS $dummy => $mo_img) {

				$pname_arr = explode('.', $mo_img['image_name']);
				$nsuffix = array_pop($pname_arr);
				$dup_products_image_name = $dup_products_id.'_'.$mo_img['image_nr'].'.'.$nsuffix;

				@copy(DIR_FS_CATALOG_ORIGINAL_IMAGES.'/'.$mo_img['image_name'], DIR_FS_CATALOG_ORIGINAL_IMAGES.'/'.$dup_products_image_name);
				@copy(DIR_FS_CATALOG_INFO_IMAGES.'/'.$mo_img['image_name'], DIR_FS_CATALOG_INFO_IMAGES.'/'.$dup_products_image_name);
				@copy(DIR_FS_CATALOG_THUMBNAIL_IMAGES.'/'.$mo_img['image_name'], DIR_FS_CATALOG_THUMBNAIL_IMAGES.'/'.$dup_products_image_name);
				@copy(DIR_FS_CATALOG_POPUP_IMAGES.'/'.$mo_img['image_name'], DIR_FS_CATALOG_POPUP_IMAGES.'/'.$dup_products_image_name);

				$this->db->db_query("INSERT INTO 
										".TABLE_PRODUCTS_IMAGES."
									SET 
										products_id = '".$dup_products_id."',
										image_nr    = '".$mo_img['image_nr']."',
										image_name  = '".$dup_products_image_name."'");
			}
		}

		$products_id = $dup_products_id;

		$i = 0;
		$group = $this->db->db_query("	SELECT 
											customers_status_id
										FROM 
											".TABLE_CUSTOMERS_STATUS."
										WHERE 
											language_id = '".(int) $_SESSION['languages_id']."'
										AND 
											customers_status_id != '0'");

		while (!$group->EOF) {
			$i++;
			$group_data[$i] = array ('STATUS_ID' => $group->fields['customers_status_id']);
			$group->MoveNext();
		}

		for ($col = 0, $n = sizeof($group_data); $col < $n +1; $col ++) {
			if ($group_data[$col]['STATUS_ID'] != '') {

				$copy = $this->db->db_query("SELECT quantity,personal_offer FROM ".TABLE_PERSONAL_OFFERS_BY.$group_data[$col]['STATUS_ID']." WHERE products_id = ".$old_products_id);

				while (!$copy->EOF) {
					$this->db->db_query("INSERT INTO 
											".TABLE_PERSONAL_OFFERS_BY.$group_data[$col]['STATUS_ID']." 
										SET 
											price_id = '',
											products_id    = '".$products_id."',
											quantity       = '".$copy->fields['quantity']."',
											personal_offer = '".$copy->fields['personal_offer']."'");
					$copy->MoveNext();
				}
			}
		}
		if(MODULE_SEO_URL_INDEX_STATUS == 'True') {
			!$seo_url ? $seo_url = new SeoUrl() : false;
			$seo_url->insertSeoDBTable('product', $products_id);
		}
	}

	function link_product($src_products_id, $dest_categories_id) {

		global $message_stack;
		$check = $this->db->db_query("SELECT 
											products_id
										FROM 
											".TABLE_PRODUCTS_TO_CATEGORIES."
										WHERE 
											products_id = ".$this->db->db_prepare($src_products_id)."
										AND 
											categories_id = ".$this->db->db_prepare($dest_categories_id));

		if (!$check->_numOfRows) {
			$this->db->db_query("INSERT INTO 
									".TABLE_PRODUCTS_TO_CATEGORIES."
								SET 
									products_id = ".$this->db->db_prepare($src_products_id).",
									categories_id = ".$this->db->db_prepare($dest_categories_id));

	    	if ($dest_categories_id == 0) {
				$this->set_product_status($src_products_id, $products_status);
				$this->set_product_startpage($src_products_id, 1);
	    	}
	    	
		} else
			$message_stack->add_session(ERROR_CANNOT_LINK_TO_SAME_CATEGORY, 'error');

	}
	
	function unlink_product_from_startpage($src_products_id) {
		global $message_stack;
		$check = $this->db->db_query("SELECT 
											products_id
										FROM 
											".TABLE_PRODUCTS_TO_CATEGORIES."
										WHERE 
											products_id = ".$this->db->db_prepare($src_products_id)."
										AND 
											categories_id = 0");

		if($check->_numOfRows) {
			$this->db->db_query("DELETE FROM 
									".TABLE_PRODUCTS_TO_CATEGORIES."
								WHERE 
									products_id = ".$this->db->db_prepare($src_products_id)."
								AND
									categories_id = '0' ");
		}
	}
	
	function move_product($src_products_id, $src_category_id, $dest_category_id) {

		$duplicate_check = $this->db->db_query("SELECT 
													products_id
												FROM 
													".TABLE_PRODUCTS_TO_CATEGORIES."
												WHERE 
													products_id   = ".$this->db->db_prepare($src_products_id)."
												AND 
													categories_id = ".$this->db->db_prepare($dest_category_id));

		if(!$duplicate_check->_numOfRows) {
			$this->db->db_query("UPDATE 
									".TABLE_PRODUCTS_TO_CATEGORIES."
								SET 
									categories_id = ".$this->db->db_prepare($dest_category_id)."
								WHERE 
									products_id = ".$this->db->db_prepare($src_products_id)."
								AND 
									categories_id = '".$src_category_id."'");

			if ($dest_category_id == 0) {
				$this->set_product_status($src_products_id, 1);
				$this->set_product_startpage($src_products_id, 1);
			}
	
			if ($src_category_id == 0) {
				 $this->set_product_status($src_products_id, $products_status);
				 $this->set_product_startpage($src_products_id, 0);
			}
		}
	}

	function set_product_status($products_id, $status) {
		if ($status == '1')
			return $this->db->db_query("UPDATE ".TABLE_PRODUCTS." set products_status = '1', products_last_modified = NOW() WHERE products_id = '".$products_id."'");
		elseif ($status == '0')
			return $this->db->db_query("UPDATE ".TABLE_PRODUCTS." set products_status = '0', products_last_modified = NOW() WHERE products_id = '".$products_id."'");
		else
			return -1;
	}

	function set_product_startpage($products_id, $status) {
		if ($status == '1')
			return $this->db->db_query("UPDATE ".TABLE_PRODUCTS." set products_startpage = '1', products_last_modified = NOW() WHERE products_id = '".$products_id."'");
		elseif ($status == '0')
			return $this->db->db_query("UPDATE ".TABLE_PRODUCTS." set products_startpage = '0', products_last_modified = NOW() WHERE products_id = '".$products_id."'");
		else
			return -1;
	}


	function count_category_products($category_id, $include_deactivated = false) {
		$products_count = 0;
		if ($include_deactivated) {
			$products = $this->db->db_query("SELECT 
												COUNT(*) AS total 
											FROM 
												".TABLE_PRODUCTS." p, 
												".TABLE_PRODUCTS_TO_CATEGORIES." p2c 
											WHERE 
												p.products_id = p2c.products_id 
											AND 
												p2c.categories_id = '".$category_id."'");
		} else {
			$products = $this->db->db_query("SELECT 
												COUNT(*) AS total 
											FROM 
												".TABLE_PRODUCTS." p, 
												".TABLE_PRODUCTS_TO_CATEGORIES." p2c 
											WHERE 
												p.products_id = p2c.products_id 
											AND 
												p.products_status = '1' 
											AND 
												p2c.categories_id = '".$category_id."'");
		}

		$products_count += $products->fields['total'];

		$childs = $this->db->db_query("SELECT categories_id FROM ".TABLE_CATEGORIES." WHERE parent_id = '".$category_id."'");
		if ($childs->_numOfRowa > 0) {
			while (!$childs->EOF)
				$products_count += $this->count_category_products($childs->fields['categories_id'], $include_deactivated);
				$childs->MoveNext();
		}
		return $products_count;
	}
	
	function checkName($name, $pID, $ext='jpg', $path=DIR_FS_CATALOG_ORIGINAL_IMAGES) {
		if(1==1 || file_exists($path.$name.'.'.$ext))
			return $name.'_'.$pID;
		else
			return $name;
	}
	
	function count_category_childs($category_id) {

		$categories_count = 0;
		$categories = $this->db->db_query("SELECT categories_id FROM ".TABLE_CATEGORIES." WHERE parent_id = '".$category_id."'");
		while (!$categories->EOF) {
			$categories_count ++;
			$categories_count += $this->count_category_childs($categories->fields['categories_id']);
			$categories->MoveNext();
		}
		return $categories_count;
	}

	function edit_cross_sell($cross_data) {


		if ($cross_data['special'] == 'add_entries') {
			if (isset ($cross_data['ids'])) {
				foreach ($cross_data['ids'] AS $pID) {
					$sql_data_array = array ('products_id' => $cross_data['current_product_id'], 
											'xsell_id' => $pID,
											'products_xsell_grp_name_id' => $cross_data['group_name'][$pID]);
											
					$check = $this->db->db_query("SELECT * FROM ".TABLE_PRODUCTS_XSELL." WHERE products_id='".$cross_data['current_product_id']."' AND xsell_id='".$pID."'");
					if ($check->_numOfRows == 0) 
						$this->db->db_perform(TABLE_PRODUCTS_XSELL, $sql_data_array);
				}
			}
		}
		if ($cross_data['special'] == 'edit') {
			if (isset ($cross_data['ids'])) {
				foreach ($cross_data['ids'] AS $pID)
					$this->db->db_query("DELETE FROM ".TABLE_PRODUCTS_XSELL." WHERE ID='".$pID."'");
			}
			if (isset ($cross_data['sort'])) {
				foreach ($cross_data['sort'] AS $ID => $sort)
					$this->db->db_query("UPDATE ".TABLE_PRODUCTS_XSELL." SET sort_order = '".$sort."',products_xsell_grp_name_id='".$cross_data['group_name'][$ID]."' WHERE ID = '".$ID."'");
			}
		}
	}
}
?>